import { ref, watch } from 'vue' 
import { useBluetoothStore } from '@/store'
import {
    getBLEDeviceCharacteristics,
    openBluetoothAdapte,
    startBluetoothDevicesDiscovery,
    getBluetoothDevices,
    getBLEDeviceServices,
    createBLEConnection
} from './bluetoothUnit'
import type { bluetootInfo } from './bluetoothUnit'


export const initBluetoot = () => {
 
    const deviceList = ref<Array<bluetootInfo>>([]) 
    const scanBluetooth = async () => {
        deviceList.value = []
        uni.showLoading()
        try {
            await openBluetoothAdapte()
            await startBluetoothDevicesDiscovery()
            const { list } = await getBluetoothDevices()
            deviceList.value = list
        }
        catch (e:any) {
            showMessage(e.msg)
            deviceList.value = []
        }
        finally {
            uni.hideLoading()
        }
    }
 

    const state = ref({
        num: 0,

        deviceId:"",
        write: false,
        read: false,
        notify: false,

        notifyCharaterId: '',
        notifyServiceId: '',

        writeCharaterId: '',
        writeServiceId: '',

        readCharaterId: '',
        readServiceId: ''

    })

    const bluetoothStore = useBluetoothStore()
    const bindDevice = async (data: any) => {
        uni.showLoading()
        try {
            await createBLEConnection(data.deviceId)
            const { services } = await getBLEDeviceServices(data.deviceId)
            state.value.num = 0

            for (var i = 0; i < services.length; i++) {
                await getBLEDeviceCharacteristics(data.deviceId, services, state)
                if (!state.value.write || !state.value.notify || !state.value.read) {
                    state.value.num++
                }
                else {
                    break
                }
            }

            if (!state.value.write || !state.value.notify || !state.value.read) {
                uni.showToast({
                	title:'找不到该读写的特征值！',
					icon:'none'
                })
            }
            else {

                // 主要是拿到这三个ID。
                // 读的，写的，通知的。之后就可以用这三个id发送指令了

                bluetoothStore.setDevice({
                    isInit: true,
                    deviceId:data.deviceId,
					
					deviceName:data.name,
					RSSI:data.RSSI,
					
                    notifyCharaterId: state.value.notifyCharaterId,
                    notifyServiceId: state.value.notifyServiceId,

                    writeCharaterId: state.value.writeCharaterId,
                    writeServiceId: state.value.writeServiceId,

                    readCharaterId: state.value.readCharaterId,
                    readServiceId: state.value.readServiceId,
                })
 
                // toPage("/pages/print/print")
				// uni.navigateBack();
				uni.navigateTo({
					url:'/pages/print'
				})
            }

        }
        catch (e) {
            console.log(e)
            uni.showToast({
            	title:'链接失败，请重试！',
				icon:'none' 
            })
			
        } finally {
            uni.hideLoading()
        }

    }

    return {
        scanBluetooth,
        deviceList,
        bindDevice
    }
}
